﻿var g_AutomationChannels = [];
var lastkeydown = -1;
var starttime = -1;
var mousemode = '';
var lastblockdelta = 0;
var lastnoteelement = null;
var lastnoteblock = null;
var lastpatternid = '';

function getCurrentPatternID() {
    var el2 = $('patterndropdown');
    var pat = el2.options[el2.selectedIndex].value;
    return pat;
}

function getCurrentInstrumentID() {
    var el2 = $('instrumentdropdown');
    var pat = el2.options[el2.selectedIndex].value;
    return pat;
}

function onReload(data) {
    console.log(data);
}

function beginReload() {
    new Ajax.Request('/api/call', {
        parameters: { 'getpatterns': '1' },
        onSuccess: onGetInitialInstrumentList
    });
}

function onPollData(r) {
    var cmd = r.responseText.split('|');
    if (cmd.length > 0) {
        if (cmd[0] == 'patternlist-changed' || cmd[0] == 'tracklist-changed') {
            beginReload();
        }
    }
    setTimeout('pollOnce()', 5000);
}

function pollOnce() {
    var sid = getCurrentSessionID();
    new Ajax.Request('/api/call', {
        parameters: { 'poll': sid },
        onSuccess: onPollData
    });
}

function beginPolling() {
    setTimeout('pollOnce()', 5000);
}



function openDeviceClicked(evt, insid, devid) {
    // alert( 'open device editor '+devid+' for instrumentid '+insid );

    for (var k = 0; k < g_DeviceUIs.length; k++) {
        var dev = g_DeviceUIs[k];
        if (dev.id == devid) {
            // alert( dev );
            var url = '/editors/' + dev.id + '/#INSTRUMENT=' + insid + '&SESSION=' + getCurrentSessionID();
            var w = window.open(url, insid + '_' + dev.id, 'WIDTH=' + dev.width + ',HEIGHT=' + dev.height + ',SCROLLING=0,RESIZE=1,SCROLLBARS=0');
            w.focus();
        }
    }
}

function openPatternEditorClicked(evt, insid, patid, edid) {
    // alert( 'open pattern editor '+edid+' for pattern '+patid+' and  instrumentid '+insid );

    for (var k = 0; k < g_EditorUIs.length; k++) {
        var ed = g_EditorUIs[k];
        if (ed.id == edid) {
            // alert( ed );
            var url = '/editors/' + ed.id + '/#PATTERN=' + patid + '&INSTRUMENT=' + insid + '&SESSION=' + getCurrentSessionID();
            var w = window.open(url, patid + '_' + ed.id, 'WIDTH=' + ed.width + ',HEIGHT=' + ed.height + ',SCROLLING=0,RESIZE=1,SCROLLBARS=0');
            w.focus();
        }
    }
}

function clickEditInstrument(evt, insid) {
    //  alert( 'pick device editor for instrument '+insid );
    var ins = getListItemID(g_Instruments, insid);

    var defdev = null;
    if (ins != null)
        defdev = getListItemID(g_DeviceUIs, ins.defaultdeviceui);

    var menu = [];

    if (defdev != null) {
        menu.push({ name: defdev[k].name, callback: openDeviceClicked.bindAsEventListener(this, insid, defdev[k].id) });
        menu.push({ name: '-' });
    }

    for (var k = 0; k < g_DeviceUIs.length; k++) {
        menu.push({ name: g_DeviceUIs[k].name, callback: openDeviceClicked.bindAsEventListener(this, insid, g_DeviceUIs[k].id) });
    }

    openPopupMenu(Event.pointerX(evt), Event.pointerY(evt), 'popupmenu', menu);
}

function clickEditPattern(evt, insid, patid) {

    //  alert( 'pick device editor for instrument '+insid );
    var ins = getListItemID(g_Instruments, insid);

    var defed = null;
    if (ins != null)
        defed = getListItemID(g_EditorUIs, ins.defaulteditorui);

    var menu = [];
    for (var k = 0; k < g_EditorUIs.length; k++) {
        menu.push({ name: g_EditorUIs[k].name, callback: openPatternEditorClicked.bindAsEventListener(this, insid, patid, g_EditorUIs[k].id) });
    }

    openPopupMenu(Event.pointerX(evt), Event.pointerY(evt), 'popupmenu', menu);
}

function clickClonePattern(evt, insid, patid) {
    alert('pick new name for pattern ' + patid + ', instrument ' + insid);
}

function cueTrackClicked(evt, insid, patid, trackid) {
    alert('cue pattern ' + patid + ' on track ' + trackid + ' (instrument ' + insid + ')');
}

function clickCuePattern(evt, insid, patid) {
    var menu = [];
    for (var k = 0; k < g_Tracks.length; k++) {
        menu.push({ name: 'Cue on: ' + g_Tracks[k].name, callback: cueTrackClicked.bindAsEventListener(this, insid, patid, g_Tracks[k].id) });
    }

    openPopupMenu(Event.pointerX(evt), Event.pointerY(evt), 'popupmenu', menu);
}

function renderPatternList() {
    var el = $('patterns');

    var table1 = document.createElement('table');

    var tr1 = document.createElement('tr');
    table1.appendChild(tr1);

    for (var j = 0; j < g_Instruments.length; j++) {
        var ins = g_Instruments[j];

        var td1 = document.createElement('td');
        td1.style.verticalAlign = 'top';
        tr1.appendChild(td1);

        var th2 = document.createElement('h2');
        th2.appendChild(document.createTextNode(ins.name));
        td1.appendChild(th2);

        var p1 = document.createElement('p');
        td1.appendChild(p1);

        var a1 = document.createElement('a');
        a1.href = '#';
        Event.observe(a1, 'click', clickEditInstrument.bindAsEventListener(this, ins.id));
        a1.appendChild(document.createTextNode('Edit device'));
        p1.appendChild(a1);

        var table2 = document.createElement('table');
        table2.className = 'grid';
        td1.appendChild(table2);

        var idx = 0;
        for (var k = 0; k < g_Patterns.length; k++) {
            var pat = g_Patterns[k];

            if (pat.instrument == ins.id) {
                var tr2 = document.createElement('tr');
                tr2.className = (idx % 2 == 0) ? 'odd' : 'even';
                table2.appendChild(tr2);

                var td21 = document.createElement('td');
                td21.appendChild(document.createTextNode(pat.name + ' (' + pat.duration + ')'));
                tr2.appendChild(td21);

                var td23 = document.createElement('td');


                var a2 = document.createElement('a');
                a2.href = '#';
                a2.appendChild(document.createTextNode('Edit'));
                Event.observe(a2, 'click', clickEditPattern.bindAsEventListener(this, ins.id, pat.id));
                td23.appendChild(a2);

                td23.appendChild(document.createTextNode(' | '));

                var a3 = document.createElement('a');
                a3.href = '#';
                a3.appendChild(document.createTextNode('Cue'));
                Event.observe(a3, 'click', clickCuePattern.bindAsEventListener(this, ins.id, pat.id));
                td23.appendChild(a3);

                td23.appendChild(document.createTextNode(' | '));

                var a4 = document.createElement('a');
                a4.href = '#';
                a4.appendChild(document.createTextNode('Clone'));
                Event.observe(a4, 'click', clickClonePattern.bindAsEventListener(this, ins.id, pat.id));
                td23.appendChild(a4);

                tr2.appendChild(td23);

                idx++;
            }
        }

        var td12 = document.createElement('td');
        tr1.appendChild(td12);
    }

    el.innerHTML = '';
    el.appendChild(table1);
}


function initPatternsView() {
    // g_Viewport = new Seq.Viewport();

    initPageHeader('PATS');

    setStatus('Initializing view...');
    // beginGetAutomationChannels();
    // beginGetInitialInstrumentList();
    // beginLoadPatternList();
    renderPatternList();
    /*
    renderInstrumentList();
    updateCurrentPattern();
	
	{
    var el = $('zoom');
    var zooms = [ 10, 20, 50, 100, 200, 400 ];
    el.options.length = 0;
    for( var k=0; k<zooms.length; k++ )
    {
    var z = zooms[k];
    el.options[ el.options.length ] = new Option( z.toString()+"%", z.toString() );
    } 
    el.selectedIndex = zooms.indexOf( 100 );
    }

	{
    var el = $('duration');
    el.value = '16';
    }
	
	beginPolling();
	
	var el1 = $('notesplaceholder');
    Event.observe( el1, 'mousemove', noteMouseMove.bindAsEventListener( this ), true );
    Event.observe( el1, 'mousedown', noteMouseDown.bindAsEventListener( this ) );
    Event.observe( el1, 'dblclick', noteDblClick.bindAsEventListener( this ) );
    Event.observe( el1, 'mouseup', noteMouseUp.bindAsEventListener( this ) );
    */
}





